<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2018/1/8
 * Time: 13:22
 */

namespace Lib\Middleware;


use Dingo\Api\Contract\Http\Request;
use JWTAuth;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Closure;
abstract class BaseGetToken extends BaseMiddleware
{
    public function handle($request, Closure $next)
    {
        if(env('APP_DEBUG'))
        {
        /*
          `$mid_params = ['park_id'=>1];
            $park_id=$request->input('park_id');
            if(!isset($park_id))
            $request->merge($mid_params);
        */
            return $next($request);
        }
        if (! $this->auth->parser()->setRequest($request)->hasToken()) {
            throw new UnauthorizedHttpException('jwt-auth', 'Token不存在');
        }
        try {
            if (! $this->auth->parseToken()->authenticate()) {
                throw new UnauthorizedHttpException('jwt-auth', '用户不存在');
            }
        } catch (JWTException $e) {
            if($e instanceof TokenExpiredException)
                throw new UnauthorizedHttpException('jwt-auth', 'token过期');
            throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
        }
        $this->Auth($request);
        return $next($request);
    }
    abstract function Auth(Request $request );
}